//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2002-2005
//
// Static control helper.
//

# include "StdAfx.h"
# include "Static.h"
# include "Wrappers.h"
# include "Globals.h"

void SetDlgItemTextF (HWND _hWnd, int _iItemId, const char * _strFormat, ...) {
	va_list vl;
	va_start (vl, _strFormat);

	char strBuf [MAX_PATH*2];
	::_vsnprintf (strBuf, sizeof (strBuf), _strFormat, vl);

	::SetDlgItemText (_hWnd, _iItemId, strBuf);

	va_end (vl);
}

	//
	// Allows to assign GIF and JPG to static control.
	//
void SetStaticPicture (HWND _hWnd, int _iItemId, WORD _wRes) {
	// Load picture from resource.
	const HRSRC hRsrc = FindResource (g_hInst, MAKEINTRESOURCE (_wRes), "PICTURE");
	const HGLOBAL hGlobal = ::LoadResource (g_hInst, hRsrc);
	const DWORD dwSize = SizeofResource (g_hInst, hRsrc);
	const void * const pData = ::LockResource (hGlobal);

	// Copy the picture to memory.
	const HGLOBAL hGlobal2 = ::GlobalAlloc (GMEM_MOVEABLE, dwSize);
	void * const pData2 = ::GlobalLock (hGlobal2);
	::memcpy (pData2, pData, dwSize);

	CCom com;

	// Create in-memory stream for the picture.
	CComPtr<IStream> pStream;
	::CreateStreamOnHGlobal (hGlobal2, TRUE, & pStream);

	// Parse the picture to in-memory bitmap.
	CComPtr<IPicture> pPicture;
	const HRESULT hr = ::OleLoadPicture (pStream, dwSize, FALSE, IID_IPicture, reinterpret_cast<void **> (& pPicture));
	if (FAILED (hr))
		return;

	// Get picture dimensions.
	OLE_XSIZE_HIMETRIC hmWidth;
	pPicture->get_Width (& hmWidth);
	OLE_YSIZE_HIMETRIC hmHeight;
	pPicture->get_Height (& hmHeight);

	// Det destination size.
	const HWND hStatic = ::GetDlgItem (_hWnd, _iItemId);
	RECT rect;
	::GetClientRect (hStatic, & rect);
	const int iWidth = rect.right - rect.left;
	const int iHeight = rect.bottom - rect.top;

	// Prepare the destination bitmap for the static control.
	const CClientDC hWndDC (hStatic);
	const CDCHolder hMemDC = ::CreateCompatibleDC (hWndDC);
	const HBITMAP hBitmap = ::CreateCompatibleBitmap (hWndDC, iWidth, iHeight);
	::SelectObject (hMemDC, hBitmap);

	pPicture->Render (hMemDC, 0, iHeight, iWidth, -iHeight - 1, 0, 0, hmWidth, hmHeight, NULL);

	// Assing the bitmap to the static control.
	const DWORD dwStyle = ::GetWindowLong (hStatic, GWL_STYLE);
	::SetWindowLong (hStatic, GWL_STYLE,  (dwStyle & ~SS_TYPEMASK) | SS_BITMAP | SS_REALSIZEIMAGE);// | SS_CENTERIMAGE);
	::SendMessage (hStatic, STM_SETIMAGE, IMAGE_BITMAP, reinterpret_cast<LPARAM> (hBitmap));
}

void DeleteStaticPicture (HWND _hWnd, int _iItemId) {
	const HBITMAP hBitmap = reinterpret_cast<HBITMAP> (::SendDlgItemMessage (_hWnd, _iItemId, STM_GETIMAGE, IMAGE_BITMAP, 0));
	if (hBitmap)
		::DeleteObject (hBitmap);
}
